package com.cj.designpattern.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * ClassName: ProxyFactory <br/>
 * Function: 动态代理工厂 <br/>
 * date: 2018/04/27 15:15 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
public class ProxyFactory<T> {

    private T t;

    public ProxyFactory(T t) {
        this.t = t;
    }

    public T getInstance() {
        Class<?> tClass = t.getClass();
        // 使用类加载器进行反射代理
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), tClass.getInterfaces(),
                (proxy, method, args) -> {
                    System.out.println("开始保存");
                    Object returnObject = method.invoke(t, args);
                    System.out.println("保存成功");
                    return returnObject;
                });
    }
}
